﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

namespace PRT {

    public static class Utils {

        public static Vector3 RandomSphere(float u, float v) {
            float theta = 2 * Mathf.Acos(1.0f - 2.0f * u);
            float Fi = 2 * Mathf.PI * v;
            float sinTheta = Mathf.Sin(theta);
            float cosTheta = Mathf.Cos(theta);
            float sinFi = Mathf.Sin(Fi);
            float cosFi = Mathf.Cos(Fi);

            //Vector3 ret = new Vector3(sinTheta * sinFi, cosTheta, sinTheta * cosFi);
            Vector3 ret = new Vector3(sinTheta * cosFi, sinTheta * sinFi, cosTheta);
            return ret;
        }

        public static Vector3 RandomSphere() {
            float u = UnityEngine.Random.Range(0, 1.0f);
            float v = UnityEngine.Random.Range(0, 1.0f);
            return RandomSphere(u, v);
        }

        public static void CollectRendersShaders<T>(T[] renderers, Dictionary<long, Shader> map) where T: Renderer {
            if (renderers == null || renderers.Length <= 0 || map == null)
                return;
            map.Clear();
            for (int i = 0; i < renderers.Length; ++i) {
                var r = renderers[i];
                long key = r.GetInstanceID();
                map[key] = r.sharedMaterial != null ? r.sharedMaterial.shader : null;
            }
        }

        public static void ChangeRendersShader<T>(T[] renderers, Shader target) where T : Renderer {
            for (int i = 0; i < renderers.Length; ++i) {
                var r = renderers[i];
                if (r.sharedMaterial != null)
                    r.sharedMaterial.shader = target;
            }
        }

        public static void ChangeRendersShaders<T>(T[] renderers, Dictionary<long, Shader> map) where T : Renderer {
            if (renderers == null || renderers.Length <= 0 || map == null || map.Count <= 0)
                return;

            for (int i = 0; i < renderers.Length; ++i) {
                var r = renderers[i];
                long key = r.GetInstanceID();
                Shader target;
                if (map.TryGetValue(key, out target) && target != null) {
                    if (r.sharedMaterial != null)
                        r.sharedMaterial.shader = target;
                }
            }
        }

#if UNITY_EDITOR
        public static void SaveCubeMap(string fileName, Cubemap map) {
            if (System.IO.File.Exists(fileName)) {
                AssetDatabase.DeleteAsset(fileName);
            }
            AssetDatabase.CreateAsset(map, fileName);
            AssetDatabase.Refresh();
        }
#endif
    }

}
